/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.faces.bean.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import model.Archive;
import model.Project;
import model.User;
import org.primefaces.event.FileUploadEvent;

@ManagedBean(name = "fileUploadController")
@ViewScoped
public class FileUploadController{

    private String destination = "/home/odiar/Public/file";//aqui vc seta onde quer gravar o arquivo
    List<String> fileList;
    private static final String OUTPUT_FOLDER = "/home/odiar/Public/file";
    Archive archive;
    List<Archive> lisArc = new ArrayList<Archive>();
    
    public void upload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);

        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            e.printStackTrace();
            
        }

    }

    public void copyFile(String fileName, InputStream in) {
        try {
            FacesContext fc = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
            User u = (User) session.getAttribute("user");
            // write the inputStream to a FileOutputStre
            
            Project p = (Project) session.getAttribute("project");
            String d;
            destination = "/home/odiar/Public/file/" + u.getEmail();
            File dir = new File(destination);
            if (!dir.exists()) {
                dir.mkdir();
            }
            
            destination = destination + "/" + p.getName();
            
            File dir2 = new File(destination);
            if (!dir2.exists()) {
                dir2.mkdir();
            }
            
            OutputStream out = new FileOutputStream(new File(destination + "/" + fileName));
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            
            unZipIt(destination + "/" + fileName, destination);
            session.setAttribute("localFile", destination);
            
            in.close();
            out.flush();
            out.close();


            System.out.println("New file created!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
        }
    }

    public void copyFileXML(String fileName, InputStream in) {
        try {
            FacesContext fc = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
            User u = (User) session.getAttribute("user");
            // write the inputStream to a FileOutputStream
            destination = "/home/odiar/Public/file/";
            destination = destination + u.getEmail();
            File dir = new File(destination);
            if (!dir.exists()) {
                dir.mkdir();
            }
            OutputStream out = new FileOutputStream(new File(destination + "/" + fileName));
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            unZipIt(destination + "/" + fileName, destination);
            session.setAttribute("localFile", destination);

            in.close();
            out.flush();
            out.close();


            System.out.println("New file created!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            
        }
    }

    public void unZipIt(String zipFile, String outputFolder) {

        byte[] buffer = new byte[1024];

        try {

            //create output directory is not exists
            File folder = new File(OUTPUT_FOLDER);
            if (!folder.exists()) {
                folder.mkdir();
            }

            //get the zip file content
            ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {

                String fileName = ze.getName();
                lisArc.add(new Archive(fileName));
                File newFile = new File(outputFolder + File.separator + fileName);

                System.out.println("file unzip : " + newFile.getAbsoluteFile());

                //create all non exists folders
                //else you will hit FileNotFoundException for compressed folder
                new File(newFile.getParent()).mkdirs();

                FileOutputStream fos = new FileOutputStream(newFile);

                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                fos.close();
                ze = zis.getNextEntry();
            }

            zis.closeEntry();
            zis.close();

            System.out.println("Done");

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public void createDir(int id_user,String projectName){
        FacesContext fc = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
            Project p = (Project) session.getAttribute("project");
        File dir = new File(p.getLocalFiles());
            if (!dir.exists()) {
                dir.mkdir();
            }
    }
    
    public List<Archive> getListArchive(){
        return lisArc;
    }
}